/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import QS from 'qs';
import store from '../store/index'
let isBoolean = false

const ysHttp = axios.create({
	baseURL:"https://open.ys7.com/api"
})
ysHttp.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
    return new Promise((resolve, reject) => {
		// console.log(config);
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
			// sslVerify: false,
            complete: function complete(response) {
                // console.log("执行完成：",response)
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };
                settle(resolve, reject, response);
            }
        })
    })
}

const http = axios.create({
    // baseURL: 'http://192.168.0.105:8090'
	baseURL: 'http://161.189.170.215:7777/api/v1.0',
    withCredentials: true, // send cookies when cross-domain requests
    crossDomain: true
})
// 环境的切换
if (process.env.NODE_ENV == 'development') {    
	//#ifdef APP-PLUS
		http.defaults.baseURL = 'http://161.189.170.215:7777/api/v1.0'
	//#endif
	//#ifdef H5
		http.defaults.baseURL = '/api/v1.0'
	//#endif
    
	
} 
// else if (process.env.NODE_ENV == 'debug') {    
//     http.defaults.baseURL = 'http://161.189.170.215:7777/api/v1.0';
// } else if (process.env.NODE_ENV == 'production') {    
//     http.defaults.baseURL = 'http://161.189.170.215:7777/api/v1.0';
// }
//需要token认证
const arr = [
	'/sc/inventory/user_oper',
	'/sc/auth/logout'
]
//请求头需要主柜id或副柜id
const slectCabId = [
	'/sc/device/heartbeat',
	'/sc/auth/login',
	'/sc/inventory/current',
	'/sc/inventory/user_oper',
	'/sc/inventory/error',
	'/sc/device',
	'/sc/user/list',
	'/sc/inventory/barcode'
]
//请求头需要主柜id
const mainCabIds = [
	'/sc/inventory/oper_log',
	'/sc/device/main/edit',
	'/sc/device/main/delete',
	'/sc/device/sub/add',
	'/sc/stats/item/consume',
	'/sc/stats/price/consume',
	'/sc/stats/item/avg_store_time',
	'/sc/stats/user/take'
]
//请求头不需要id
const nullCabIds = [
	'/sc/auth/logout',
	'/sc/device/main/add',
	'/sc/device/sub/edit',
	'/sc/device/sub/delete'
]
// 请求超时时间
http.defaults.timeout = 10000;

// post请求头
http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
http.interceptors.request.use(    
    config => {
        // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
        // 即使本地存在token，也有可能token是过期的，所以在响应拦截器中要对返回状态进行判断
		
		console.log(config);
		let data=null
		if(config.method=="post"){
			if(!isBoolean){
				data=QS.parse(config.data)
			}else{
				data=config.data
			}
		}else{
			data=config.params
		}
		// console.log(data);
		let token = null
		console.log(data.terminalId);
		if(!!data.terminalId){
			console.log("ss");
			config.headers.terminalId=data.terminalId
			// config.header.terminalId=data.terminalId
			let tokenData = uni.getStorageSync('token'+data.terminalId);
			console.log(tokenData);
			if(tokenData&&tokenData.tokenId){
				token=tokenData.tokenId
			}
			// console.log(config);
			
		}
		// if(config.url !== '/sc/auth/logout') {
		// 	config.headers['terminalId'] = '1'
		// }
		// if(mainCabIds.includes(config.url)){
		// 	config.headers['terminalId'] = '1'
		// }else if(slectCabId.includes(config.url)){
		// 	config.headers['terminalId'] = 
		// }
		
		if(isBoolean){
			config.headers['Content-Type']= "application/json";
			isBoolean = false
		}
		if(arr.includes(config.url)){
			if(token) {
				config.headers['token'] = token
				// config.headers.Authorization = token
			}
		}
		const cookie = uni.getStorageSync('cookie')
		if(cookie){
			config.headers.Cookie = cookie
		}
		// console.log(config);
        return config;    
    },    
    error => {   
		console.log(error);
        return Promise.error(error);    
    })

// 响应拦截器 
http.interceptors.response.use(    
    response => {  
		// console.log(response)
      if (response.status === 200) {
			if(response.config.url=='/auth/login'){
				// console.log(response.config.url)
				// console.log(response.header['Set-Cookie'])
				uni.setStorageSync("cookie",response.header['Set-Cookie'])
			}
            return Promise.resolve(response);        
        } else {            
            return Promise.reject(response);        
        }    
    },
    // 服务器状态码不是200的情况
    error => {      
			console.log(error);
    }
);

http.defaults.adapter = function(config) { //自己定义个适配器，用来适配uniapp的语法
    return new Promise((resolve, reject) => {
		// console.log(config);
        var settle = require('axios/lib/core/settle');
        var buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method: config.method.toUpperCase(),
            url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
            header: config.headers,
            data: config.data,
            dataType: config.dataType,
            responseType: config.responseType,
            sslVerify: config.sslVerify,
			// sslVerify: false,
            complete: function complete(response) {
                // console.log("执行完成：",response)
                response = {
                    data: response.data,
                    status: response.statusCode,
                    errMsg: response.errMsg,
                    header: response.header,
                    config: config
                };
                settle(resolve, reject, response);
            }
        })
    })
}

/** 
 * get方法，对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function get(url, params){    
    return new Promise((resolve, reject) =>{   
        http.get(url, {            
            params: params     
        })        
        .then(res => { 
            resolve(res.data);        
        })        
        .catch(err => {            
            reject(err.data)        
        })    
    });
}
/** 
 * post方法，对应post请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
export function post(url, data, isjson=false) {    
    return new Promise((resolve, reject) => {
		isBoolean=isjson
		if(isjson) {
			http.post(url, data)
			.then(res => {
			    resolve(res.data);        
			})        
			.catch(err => {
				reject(err)
			})  
		}else{
			http.post(url, QS.stringify(data))
			.then(res => {
				// console.log(url);
			    resolve(res.data);        
			})        
			.catch(err => {
				console.log(10,err);
				reject(err)
			          
			})  
		}        
          
    });
}
export { ysHttp }
